import os
import re

# 定义品牌目录和输出文件路径
BRANDS_DIR = 'e:/open/MobileModels/aa'
OUTPUT_FILE = 'e:/open/MobileModels/aa.txt'

# 清理输出文件
if os.path.exists(OUTPUT_FILE):
    os.remove(OUTPUT_FILE)

# 定义要排除的文件
EXCLUDE_FILES = ['xiaomi-wear.md', 'mitv_cn.md', 'mitv_global_en.md']

# 定义获取品牌名的函数
def get_brand_from_filename(filename):
    # 移除文件扩展名
    brand = filename.split('.')[0]
    # 处理特殊情况
    brand_map = {
        '360shouji': '360手机',
        'apple_all': 'Apple',
        'apple_all_en': 'Apple',
        'apple_cn': 'Apple',
        'asus_cn': 'ASUS',
        'asus_en': 'ASUS',
        'blackshark': '黑鲨',
        'blackshark_en': '黑鲨',
        'coolpad': '酷派',
        'google': 'Google',
        'honor_cn': '荣耀',
        'honor_global_en': '荣耀',
        'huawei_cn': '华为',
        'huawei_global_en': '华为',
        'lenovo': '联想',
        'letv': '乐视',
        'meizu': '魅族',
        'meizu_en': '魅族',
        'motorola': '摩托罗拉',
        'nokia': '诺基亚',
        'nothing': 'Nothing',
        'nubia': '努比亚',
        'oneplus': '一加',
        'oneplus_en': '一加',
        'oppo_cn': 'OPPO',
        'oppo_global_en': 'OPPO',
        'realme_cn': 'realme',
        'realme_global_en': 'realme',
        'samsung_cn': '三星',
        'samsung_global_en': '三星',
        'smartisan': '锤子',
        'sony_cn': '索尼',
        'vivo_cn': 'vivo',
        'vivo_global_en': 'vivo',
        'xiaomi': '小米',
        'xiaomi_en': '小米',
        'zhixuan': '华为智选',
        'zte': '中兴'
    }
    return brand_map.get(brand, brand)

# 遍历品牌目录下的所有文件
for filename in os.listdir(BRANDS_DIR):
    if filename.endswith('.md') and filename not in EXCLUDE_FILES:
        file_path = os.path.join(BRANDS_DIR, filename)
        brand = get_brand_from_filename(filename)
        
        try:
            # 读取文件内容
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.readlines()
                
            # 处理文件内容
            for line in content:
                line = line.strip()
                # 匹配格式: `型号: 商品名`
                match = re.match(r'`([^`]+)`:\s*(.+)', line)
                if match:
                    device_model = match.group(1).strip()
                    product_name = match.group(2).strip()
                    # 写入输出文件
                    with open(OUTPUT_FILE, 'a', encoding='utf-8') as out_f:
                        out_f.write(f"{device_model}|{brand}|{product_name}|0\n")
        except Exception as e:
            print(f"处理文件 {filename} 时出错: {e}")

print(f"处理完成，结果已保存到 {OUTPUT_FILE}")